package com.zzc.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限会跳到登录页面
        //自定义登录界面，登录url("/tologin")
        /*
         * 默认参数名username，password
         * 自定义参数名http.formLogin().usernameParameter("xxx").passwordParameter("xxx").loginPage("/tologin");
         */
        http.formLogin().loginPage("/tologin");
        //http.formLogin();默认登录界面，默认登录url（"/login"）
        //http.formLogin().loginPage("/tologin").loginProcessingUrl("/xxx");自定义登陆界面，登录url

        //注销,如果报错改post请求或者 http.csrf().disable(); 关闭csrf功能
        http.csrf().disable();
        //自定义注销成功放回界面
        http.logout().logoutSuccessUrl("/");

        //添加记住我功能
        //http.rememberMe().rememberMeParameter("xxx") 自定义rememberMe属性名，默认"remember-me"
        http.rememberMe();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //在内存中添加用户
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("zzc").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123")).roles("vip1");
    }
}
